package com.richpencil.utils;
import java.io.StringReader;
import java.security.DigestException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import com.richpencil.sqlsearch.SQLStatementItem;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.alibaba.fastjson.JSON;

public class StringHelper {


	public static String resetValue(String value){

		if(StringHelper.IsEmptyOrNull(value))
			return "";
		else
			return value;
	}
	public static String resetValue(Integer value){

		if(StringHelper.IsEmptyOrNull(value))
			return "";
		else
			return value.toString();
	}
	public static boolean IsOperate(String a){

		boolean ret=false;
		List<String> op= Lists.newArrayList(">=","<=",">","<","like","!=","=","where","\t","%","or","and"," ");
		for(String s:op)
		{
			if((StringUtils.equals(a, s)))
			{
				ret=true;
				break;
			}
		}
		return ret;
	}
	public static void SetOperate(int k, String[] array, List<String> fixs, SQLStatementItem item)
	{
		int pos=k;
		String v=array[pos];
		while(StringHelper.IsOperate(v))
		{
			fixs.remove(fixs.size()-1);
			item.beforeOp=item.beforeOp+v;
			pos--;
			v=array[pos];
		}
	}
	public static int SetOperateAfter(int k, String[] array, List<String> fixs, SQLStatementItem item)
	{
		int pos=k;
		String v=array[pos];
		List<String> l=Lists.newArrayList();
		while(StringHelper.IsOperate(v))
		{
			l.add(v);
			pos--;
			fixs.remove(fixs.size()-1);
			//item.afterOp=item.afterOp+v;
			v=array[pos];
		}
		for(int i=l.size()-1;i>=0;i--)
		{
			String s=l.get(i);
			item.afterOp=item.afterOp+s;
		}
		return pos;
	}


	public static String getParamName(String s)
	{

		int startleft=StringUtils.indexOf(s, "{");
		int startright=StringUtils.indexOf(s, "}");
		String v=StringUtils.substring(s,startleft+1,startright);
		return v;


	}


	public static String[] getStringArray(String search)
	{
		List<String> op= Lists.newArrayList(">","<",">=","<=","="," where ","\t","%","!="," or "," and "," like "," select "," update "," insert "," left "," outer "," join ");
		search= org.apache.commons.lang3.StringUtils.replace(search, "\t", " ");
		search=search.toLowerCase();
		for(String s:op)
		{
			search= org.apache.commons.lang3.StringUtils.replace(search, s, " "+s+" ");
		}
		String[] array= StringUtils.split(search, " ");
		return array;
	}
	public static boolean checkIsIndexof(int ret){

		if(ret==-1)
			return false;
		else
			return true;

	}

	public String toUpper(String Key)
	{
		return Key.toLowerCase();
		
	}
	/**
	 * 描述: 将string类型的XML转为Map 说明：将string类型的XML转为Map 最近修改时间: 2016-09-06 修改者：王丘轲
	 * 创建时间：2016-09-06 创建者：王丘轲
	 * 
	 * @param str_XML
	 *            XML字符串(格式:<xml><xml1>data1</xml1><xml2>data2</xml2></xml>)
	 * @return
	 */
	public static Map<String, Object> getXMLToMap(String str_XML) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			SAXReader saxReader = new SAXReader();
			Document document = null;
			document = saxReader.read(new StringReader(str_XML));
			Element root = (Element) document.getRootElement();
			List list_Node = root.elements();
			for (int i = 0; i < list_Node.size(); i++) {
				Element node = (Element) list_Node.get(i);
				String str_Name = node.getName();
				String str_Data = node.getData().toString();
				map.put(str_Name, str_Data);
			}
		} catch (Exception e) {
			map = new HashMap<String, Object>();
		}
		return map;
	}

	/**
	 * 描述：获得任意年月日时分秒至今的秒数
	 * 说明：获得任意年月日时分秒至今的秒数
	 * 最近修改时间:	2016-09-07
	 * 修改者：王丘轲
	 * 创建时间：2016-09-07
	 * 创建者：王丘轲
	 * @param str_BeignDate 起始日期(格式:yyyy-MM-dd HH:mm:ss)
	 * @return
	 */
	public static String getSecondByCustomYear(String str_BeignDate) {
		String str_Result = "";
		try{
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date date1 = df.parse(str_BeignDate);
			Date date2 = df.parse(df.format(new Date()));
			if(date1.getTime() > date2.getTime()){
				str_Result = "0";
			}
			else{
				long diff = date2.getTime() - date1.getTime();
				str_Result = (diff/1000) + "";
			}
		}
		catch(Exception e){
			str_Result = "";
		}
		return str_Result;
	}
	
	/**
	 * 描述:	生成随机字符串
	 * 说明：生成随机字符串
	 * 最近修改时间:	2016-09-06
	 * 修改者：王丘轲
	 * 创建时间：2016-09-06
	 * 创建者：王丘轲
	 * @param int_Length 返回字符串的长度
	 * @return
	 */
	public static String getRandomString(int int_Length) {
    	StringBuffer sb_Result = new StringBuffer();   
		String str_RandomRange = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
		Random random = new Random();
		int int_Num = 0;
		while(int_Num < int_Length){
			int int_RandomNum = random.nextInt(str_RandomRange.length());
			sb_Result.append(str_RandomRange.charAt(int_RandomNum));
			int_Num++;
		}
		return sb_Result.toString();
	}
	/**
	 * 描述：JSON字符串转为Map
	 * 说明：适用于获得一级参数时应用
	 * 最近修改时间:	2016-10-12
	 * 修改者：王丘轲
	 * 创建时间：2016-10-12
	 * 创建者：王丘轲
	 * @param jsonStr字符串JSON
	 * @return
	 */
	public static Map jsonStr2Map(String jsonStr){
		return JSON.parseObject(jsonStr, Map.class);
	}
	public static String getImage_c_(String imageUrl){
		String url = "";
		try{
			if(imageUrl != null && imageUrl.length() > 0){
				Integer lastNum = imageUrl.lastIndexOf(".");
				String before  = imageUrl.substring(0, lastNum).toString();
				String after = imageUrl.substring(lastNum).toString();
				url = imageUrl.substring(0, lastNum).toString() + "_c_" + after;
			}
		}catch(Exception e){
			url = "";
		}
		return url;
	}	
	public static String SHA1(Map<String, Object> maps) throws DigestException {  
		//获取信息摘要 - 参数字典排序后字符串  
		String decrypt = getOrderByLexicographic(maps);  
		try {  
			//指定sha1算法  
			MessageDigest digest = MessageDigest.getInstance("SHA-1");  
			digest.update(decrypt.getBytes());  
			//获取字节数组  
			byte messageDigest[] = digest.digest();  
			// Create Hex String  
			StringBuffer hexString = new StringBuffer();  
			// 字节数组转换为 十六进制 数  
			for (int i = 0; i < messageDigest.length; i++) {  
				String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);  
				if (shaHex.length() < 2) {  
					hexString.append(0);  
				}  
				hexString.append(shaHex);  
			}  
			return hexString.toString().toUpperCase();  
  
		} catch (NoSuchAlgorithmException e) {  
			e.printStackTrace();  
			throw new DigestException("签名错误！");  
		}  
    }
	private static String getOrderByLexicographic(Map<String,Object> maps)
	{  
		System.out.println(splitParams(lexicographicOrder(getParamsName(maps)),maps));
		//jsapi_ticket=sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg&noncestr=Wm3WZYTPz0wzccnW&timestamp=1414587457&url=http://mp.weixin.qq.com?params=value
		//jsapi_ticket=sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg&noncestr=Wm3WZYTPz0wzccnW&timestamp=1414587457&url=http://mp.weixin.qq.com?params=value
		return splitParams(lexicographicOrder(getParamsName(maps)),maps);  
    }
	private static List<String> getParamsName(Map<String,Object> maps){  
        List<String> paramNames = new ArrayList<String>();  
        for(Map.Entry<String,Object> entry : maps.entrySet()){  
            paramNames.add(entry.getKey());  
        }  
        return paramNames;  
    }
	private static List<String> lexicographicOrder(List<String> paramNames){  
		Collections.sort(paramNames);  
		return paramNames;  
	}
	private static String splitParams(List<String> paramNames,Map<String,Object> maps){  
		StringBuilder paramStr = new StringBuilder();  
		for(String paramName : paramNames){  
			paramStr.append(paramName);  
			for(Map.Entry<String,Object> entry : maps.entrySet()){  
				if(paramName.equals(entry.getKey())){  
					paramStr.append("="+String.valueOf(entry.getValue())+"&");  
				}  
			}  
		}  
		paramStr.deleteCharAt(paramStr.length()-1);
		return paramStr.toString();  
	}	
	public static boolean IsEmptyOrNull(String value)
	{
		
		if(value==null||"".equals(value)||"null".equals(value))
		{
			return true;
		}
		else
		{
			return false;
		}
		
		
	}
	public static boolean IsEmptyOrNull(Object value)
	{
		
		if(value==null||"".equals(value.toString()))
		{
			return true;
		}
		else
		{
			return false;
		}
		
		
	}
	
	public static String getStringValue(Object value)
	{
		
		if(value==null)
		{
			return "";
		}
		else
		{
			return value.toString();
		}
		
		
		
	}

	
	
}
